import { BaseSystem } from '../base';
import { emitEventConfig, EVENTS, type IEventBus } from '../../events';
import type {
  PlayerAttributesModel,
  PlayerProgressModel,
  RealmModel,
} from '../../model';
import { RealmReader } from '../../model/realm/realm-reader';
import type { PlayerStateSystem } from '../player-state';
import { MODEL_NAME } from '../../constants/model-names';

export class RealmSystem extends BaseSystem {
  private bus: IEventBus;
  private playerStateSystem: PlayerStateSystem;

  constructor(bus: IEventBus, playerStateSystem: PlayerStateSystem) {
    super();
    this.bus = bus;
    this.playerStateSystem = playerStateSystem;

    this.bus.on(EVENTS.REALM_BREAKTHROUGH, () => {
      const realmModel = this.playerStateSystem.getModel<RealmModel>(
        MODEL_NAME.REALM
      );
      const playerAttributesModel =
        this.playerStateSystem.getModel<PlayerAttributesModel>(
          MODEL_NAME.PLAYER_ATTRIBUTES
        );
      const playerProgressModel =
        this.playerStateSystem.getModel<PlayerProgressModel>(
          MODEL_NAME.PLAYER_PROGRESS
        );
      const result = realmModel.breakRealm();
      if (!result) return;
      const currentRealm = realmModel.getCurrentRealmInfo();
      if (!currentRealm) return;
      /** 更新属性 */
      const realm = realmModel.getRealm();
      const realmConfig = RealmReader.getRealmConfigByLevel(realm);
      playerAttributesModel.setRealm(
        realmConfig.bigLevelType,
        realmConfig.smallLevel
      );
      /** 更新玩家进度 */
      playerProgressModel.setRealm(realm);
      /** 触发境界配置中的事件 */
      const event = currentRealm.event || [];
      emitEventConfig(event);
    });
  }
}
